<template>
  <div class="warpper-box">
    <div class="inner_box">
   
    <div class="dun-box">
      <el-card class="box-flex">
        <div slot="header" class="clearfix">
          <span class="front-title">系统logo</span>
            <el-button size="mini" style="float:right" type="primary" @click="submitForm()"
              >立即创建</el-button
            >
        </div>
        <el-upload
          accept="image/*"
          action="#"
          :show-file-list="false"
          :http-request="onChangeFile"
          :before-upload="beforeAvatarUpload"
        >
          <div class="upload-box">
            <el-button type="primary" size="mini">上传</el-button>
            <div class="el-upload__tip">只支持图片</div>
          </div>
          <img
            v-if="ruleForm.logo"
            :src="ruleForm.logo"
            class="logo-avatar"
          />
        </el-upload>
      </el-card>
      <el-card class="box-flex">
        <div slot="header" class="clearfix">
          <span class="front-title">系统名称设置</span>
          <el-button
            style="float:right"
            size="mini"
            type="primary"
            @click="submitForm()"
            >立即创建</el-button
          >
        </div>
        <el-input
          type="textarea"
          :rows="4"
          v-model="ruleForm.sysName"
        ></el-input>
      </el-card>
    </div>

    <div class="dun-box box-cards">
      <el-card class="box-flex">
        <div slot="header" class="clearfix">
          <span class="front-title">网站首页banner</span>
          <div style="float:right">
            <el-button size="mini" type="primary" @click="submitForm()"
              >立即创建</el-button
            >
          </div>
        </div>
        <el-upload
          accept="image/*"
          list-type="picture"
          :on-preview="handlePreview"
          :file-list="homeFileList"
          :before-upload="homeBeforeUpload"
          :on-remove="homeRemove"
          action="#"
          :http-request="homeChangeFile"
        >
          <div class="upload-box">
            <el-button type="primary" size="mini">上传</el-button>
            <div class="el-upload__tip">只支持图片，宽高1920*700</div>
          </div>
        </el-upload>
      </el-card>
      <el-card class="box-flex">
        <div slot="header" class="clearfix">
          <span class="front-title">系统登录banner</span>
          <el-button
            style="float:right"
            size="mini"
            type="primary"
            @click="submitForm()"
            >立即创建</el-button
          >
        </div>
        <el-upload
          accept="image/*"
          list-type="picture"
          :on-preview="handlePreview"
          :file-list="loginFileList"
          :before-upload="loginBeforeUpload"
          action="#"
          :on-exceed="handleExceed"
          :on-remove="loginRemove"
          :limit="1"
          :http-request="loginChangeFile"
        >
          <div class="upload-box">
            <el-button type="primary" size="mini">上传</el-button>
            <div class="el-upload__tip">只支持图片，宽高1920*900</div>
          </div>
        </el-upload>
      </el-card>
    </div>

    <el-card class="box-cards">
      <div slot="header" class="clearfix">
        <span class="front-title">供应商注册，须知设置</span>
        <el-button
          style="float:right"
          size="mini"
          type="primary"
          @click="submitForm()"
          >立即创建</el-button
        >
      </div>
      <quill-editor
        style="display: inline-block;width: 100%;height: 400px;"
        v-model="ruleForm.supplierInfo"
        :options="editorOption"
      ></quill-editor>
    </el-card>
    <el-card class="box-cards">
      <div slot="header" class="clearfix">
        <span class="front-title">网站底部信息设置</span>
        <el-button
          style="float:right"
          size="mini"
          type="primary"
          @click="submitForm()"
          >立即创建</el-button
        >
      </div>

      <quill-editor
        style="display: inline-block;width: 100%;height: 400px;"
        v-model="ruleForm.footerInfo"
        :options="editorOption"
        ref="footerRef"
      ></quill-editor>
    </el-card>
     </div>
    <el-dialog title="图片预览" :visible.sync="dialogVisible">
      <img :src="previewUrl" alt="图片预览" class="previcew-img" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters, mapActions } from "vuex";
import { getDetailByKey, systemSupplierInfoSave } from "@/api/about_api";
import { toolbarOptions, handlers } from "@/utils/index";
export default {
  name: "webInfo",
  data() {
    return {
      ruleForm: {
        supplierInfo: "",
        footerInfo: "",
        sysName: "",
        logo: "",
        homebanner: "",
        loginbanner: "",
      },
      ruleList: [],
      homeFileList: [],
      loginFileList: [],
      dialogVisible: false,
      previewUrl: "",
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions,
            handlers: handlers
          }
        },
        theme: "snow"
      },
      allowedFormats: ['image/jpeg', 'image/png', 'image/gif','image/jpg']
    };
  },
  computed: {
    ...mapGetters(["uploadType"])
  },
  mounted() {
     this.getInfo();
  },
  methods: {
    ...mapActions({
      uploadFile: "user/uploadFile"
    }),
    async getInfo() {
       this.homeFileList = []
      this.loginFileList = []
      for (let key in this.ruleForm) {
          this.getKeyResult(key)
        }
    },
    getKeyResult(dataKey) {
       return new Promise(async (resolve, reject) => {
        let { code, data } = await getDetailByKey(dataKey);
         if (code === 200) {
           var pwdblank = /^\S*$/;
           if (dataKey == 'homebanner') {
             if (!pwdblank.test(data.value)) { 
                this.homeFileList = []
             } else {
                 if (data && data.value) {
                  this.homeFileList = JSON.parse(data.value)
                }
             }

           } else if (dataKey == 'loginbanner') {
             if (!pwdblank.test(data.value)) {
               this.loginFileList = []
             } else { 
              if (data && data.value) {
                this.loginFileList = JSON.parse(data.value)
              }
             }
            } else {
              this.ruleForm[data.key] = data?.value
           }
           if (data) {
             const rule = this.ruleList.map(v => v.id)
             if (!rule.includes(data.id)) {
                this.ruleList.push(data)
               }
           }
          resolve(true);
        }
      });
    },
    handlePreview(file) {
      this.previewUrl = file.url;
      this.dialogVisible = true;
    },
    async homeChangeFile(file, fileList) {
      let fileKey = this.uploadType['homeBanner']
      const url = await this.uploadFile({ fileKey: fileKey, data: file });
      if (url) {
        this.homeFileList.push({ name: file.file.name, url: url });
      }
    },
    async loginChangeFile(file, fileList) {
      let fileKey = this.uploadType['loginBanner']
      const url = await this.uploadFile({ fileKey: fileKey, data: file });
      if (url) {
        this.loginFileList.push({ name: file.file.name, url: url });
      }
    },
    homeRemove(file, fileList) {
      const index = this.homeFileList.indexOf(file);
      if (index > -1) {
        this.homeFileList.splice(index, 1);
      }
    },
    loginRemove(file, fileList) {
      const index = this.loginFileList.indexOf(file);
      if (index > -1) {
        this.loginFileList.splice(index, 1);
      }
    },
    async onChangeFile(file, fileList) {
      let fileKey = this.uploadType['logo']
      const url = await this.uploadFile({ fileKey:fileKey, data: file });
      if (url) {
        this.ruleForm.logo = url;
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `系统登录banner背景图只能上传一个，请删除图片后再上传。`
      );
    },
    loginBeforeUpload(file) {
      return new Promise((resolve, reject) => {
        if (!this.allowedFormats.includes(file.type)) {
          this.$message.error(`仅支持 ${this.allowedFormats.join(',')} 格式的图片`);
          reject();
          return;
        }
        const minWidth = 1900
        const minHeight = 890
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (e) => {
          const img = new Image();
          img.src = e.target.result;
          img.onload = () => {
            const width = img.width;
            const height = img.height;
            if (width < minWidth || height < minHeight) {
              this.$message.error(`图片尺寸不能小于${minWidth}x${minHeight}px`);
              reject();
            } else {
              resolve();
            }
          };
        };
      });
    },
    homeBeforeUpload(file) {
      return new Promise((resolve, reject) => {
        if (!this.allowedFormats.includes(file.type)) {
          this.$message.error(`仅支持 ${this.allowedFormats.join(',')} 格式的图片`);
          reject();
          return;
        }
        const minWidth = 1900
        const minHeight = 670
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (e) => {
          const img = new Image();
          img.src = e.target.result;
          img.onload = () => {
            const width = img.width;
            const height = img.height;
            if (width < minWidth || height < minHeight) {
              this.$message.error(`图片尺寸不能小于${minWidth}x${minHeight}px`);
              reject();
            } else {
              resolve();
            }
          };
        };
      });
    },
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/jpg";
      if (!isJPG) {
        this.$message.error("图片只能是 jpeg，png，jpg 格式!");
      }
      return isJPG;
    },
    async submitForm() {
      let result = []
      for (let key in this.ruleForm) {
        let params = {};
          let obj = this.ruleList.find(v => v.key == key)
            if (obj) {
              params.id = obj.id
            }
        if (key == 'homebanner') {
          if (this.homeFileList.length) { 
            params.value = JSON.stringify(this.homeFileList)
            params.key = key
            result.push(params)
          } else {
            params.value = ' '
            params.key = key
            result.push(params)
          }
        } else if (key == 'loginbanner') {
          if (this.loginFileList.length) {
            params.value = JSON.stringify(this.loginFileList)
            params.key = key
            result.push(params)
          } else {
            params.value = ''
            params.key = key
            result.push(params)
          }
        } else {
          if (this.ruleForm[key]) {
            params.value = this.ruleForm[key]
            params.key = key
            result.push(params)
          }
        }
      }
      const { code } = await systemSupplierInfoSave(result);
      if (code === 200) {
        if (this.ruleForm.logo) {
          this.$store.dispatch('settings/setLogo',this.ruleForm.logo)
        }
        this.$message.success("操作成功");
        this.getInfo();
      }
    }
  }
};
</script>
<style scoped>
.box-cards {
  margin-top: 15px;
}
.box-flex + .box-flex {
  margin-left: 15px;
}
.box-flex {
  flex: 1;
}
.front-title {
  font-weight: bold;
  display: inline-block;
  font-size: 18px;
}
.dun-box {
  display: flex;
}
.upload-box {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}
.el-upload__tip {
  font-size: 13px;
  margin-left: 8px;
  margin-top: 0;
  font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, SimSun, sans-serif;
    font-weight: 400;
}
.logo-avatar {
  max-width: 100%;
  filter: drop-shadow(2px 4px 6px black);
}
</style>
